import { QuestionCircleOutlined } from '@ant-design/icons';
import { Card, Space, Steps, Button, Checkbox, message, Radio, Image, Modal } from 'antd';
import Table, { ColumnsType } from 'antd/es/table';
import { TableRowSelection } from 'antd/es/table/interface';
import axios from 'axios';
import { useEffect, useState } from 'react';

import commonService from '@/api/services/commonService';
import { useCommon } from '@/hooks/common';
import { NAV_WIDTH } from '@/layouts/dashboard/config';
import userStore from '@/store/userStore';
import { toYuan } from '@/utils/format-number';

import { AddressModal } from '../address/modal';

import { renderColumn } from './column';

export default function CartPage() {
  const uri = 'cart';
  const { data = [], doDel, refetch } = useCommon({ code: '' }, uri, {});

  const [selectedRowKeys, setSelectedRowKeys] = useState<any>([]);
  const [isCheckAll, setIsCheckAll] = useState<boolean>(false);
  const [checked, setChecked] = useState<any>([]);
  const [addressShow, setAdressShow] = useState(false);
  const [tree, setTree] = useState([]);
  const [fee, setFee] = useState(0);
  const [express, setExpress] = useState([]);
  const [order, setOrder] = useState<any>({});
  const [payType, setPayType] = useState('wechat');
  const [payData, setPayData] = useState<any>({});
  const [orderInfo, setOrderInfo] = useState<any>({});
  const [step, setStep] = useState<number>(0);
  const [coupon, setCoupon] = useState<number>(0);
  const [showPay, setShowPay] = useState<boolean>(false);
  const [payUrl, setPayUrl] = useState('');
  const [visible, setVisible] = useState<boolean>(false);
  const [pic, setPic] = useState<string>('');

  useEffect(() => {
    refetch();
  }, []);

  const handleBatchDelete = () => {
    if (!checked.length) {
      message.error('请选择商品！');
    }
    const ids = checked.map((item: any) => {
      return item.id;
    });
    Modal.confirm({
      title: '确定删除勾选的商品吗？',
      centered: true,
      onOk() {
        doDel(ids.join(','));
      },
    });
  };

  const handleAddressModalClose = async (values: any) => {
    await commonService.addApi('address', values);
    setAdressShow(false);
    const ids = checked.map((item: any) => {
      return item.id;
    });
    commonService
      .getCustomApi('/member/cart/settlement', { cartIds: ids.join(',') })
      .then((res) => {
        setOrderInfo(res);
      });
  };

  const doOrder = () => {
    if (!checked.length) {
      message.error('请选择商品！');
    }
    const ids = checked.map((item: any) => {
      return item.id;
    });
    commonService
      .getCustomApi('/member/cart/settlement', { cartIds: ids.join(',') })
      .then((res) => {
        const isDefaultInfo = res.memberAddressList?.find((v: any) => v.isDefault === 1);
        if (isDefaultInfo) {
          commonService
            .getCustomApi('/member/freightTemplate/getFreightTemplateList', {
              userAddressId: isDefaultInfo.id,
            })
            .then((res) => {
              setExpress(res);
            });
        }
        setOrder({
          ...order,
          cartIds: ids.join(','),
          packageId: 2,
          memberAddressId: isDefaultInfo?.id,
        });
        setOrderInfo(res);
        setStep(1);
        commonService.getCustomApi('/member/area/getTree', {}).then((res) => {
          setTree(res);
        });
      });
  };

  const submitOrder = () => {
    if (!order.memberAddressId) {
      message.error('请选择收货地址！');
      return;
    }
    if (!order.ftId) {
      message.error('请选择配送方式！');
      return;
    }
    commonService.postCustomApi('/member/order/confirmOrder', order).then((res) => {
      commonService.getCustomApi('/member/pay/pay', { orderNumber: res.orderNumber }).then((re) => {
        setPayData({ ...res, balance: re.balance, totalMoney: re.totalMoney });
      });
      setStep(2);
    });
  };

  const toPay = () => {
    switch (payType) {
      case 'balance':
        commonService
          .getCustomApi('/member/pay/balancePay', { orderNumber: payData.orderNumber })
          .then((res) => {
            message.success('支付成功');
            window.location.href = `/#/admin/order`;
          });
        break;
      case 'alipay':
        const token = userStore.getState().userToken;
        axios({
          baseURL: import.meta.env.VITE_APP_BASE_API,
          timeout: 50000,
          method: 'get',
          url: `/member/pay/alipay?orderNumber=${payData.orderNumber}`,
          headers: {
            'Content-Type': 'application/json;charset=utf-8',
            Authorization: `Bearer ${token.accessToken}`,
          },
        }).then((res: any) => {
          if (res.data) {
            const newWindow: any = window.open('', '_blank');
            newWindow.document.write(res.data);
            newWindow.document.close();
            checkStatus();
          } else {
            message.error('操作失败');
          }
        });
        break;
      default:
        commonService
          .getCustomApi('/member/pay/wxPay', { orderNumber: payData.orderNumber })
          .then((res) => {
            setPayUrl(res);
            setShowPay(true);
            checkStatus();
          });
    }
  };

  const checkStatus = () => {
    commonService
      .getCustomApi(
        '/member/order/listenOrder',
        { orderNumber: payData.orderNumber },
        { noError: true },
      )
      .then(() => {
        message.success('支付成功!');
        setShowPay(false);
        // window.location.reload();
        window.location.href = `/#/admin/order`;
      })
      .catch(() => {
        setTimeout(() => {
          checkStatus();
        }, 3000);
      });
  };

  const columns: ColumnsType<any> = renderColumn(refetch, doDel);

  // rowSelection objects indicates the need for row selection
  const rowSelection: TableRowSelection<any> = {
    selectedRowKeys,
    onChange: (selectedRowKeys, selectedRows) => {
      setSelectedRowKeys(selectedRowKeys);
      setIsCheckAll(selectedRowKeys.length === data.length);
      console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows);
    },
    onSelect: (record, selected, selectedRows) => {
      setChecked(selectedRows);
      console.log(record, selected, selectedRows, 111);
    },
    onSelectAll: (selected, selectedRows, changeRows) => {
      setChecked(selectedRows);
      console.log(selected, selectedRows, changeRows, 222);
    },
  };

  const handleCheckAll = (e: any) => {
    setIsCheckAll(e.target.checked);
    if (e.target.checked) {
      setSelectedRowKeys(data.map((item: any) => item.id));
      setChecked(data);
    } else {
      setSelectedRowKeys([]);
      setChecked([]);
    }
  };

  return (
    <Space direction="vertical" size="large" className="w-full  pb-[120px]">
      <Card title="购物车" bordered={false}>
        <div className="mb-[20px] pl-[60px] pr-[60px]">
          <Steps
            current={step}
            labelPlacement="vertical"
            items={[{ title: '查看购物信息' }, { title: '确认订单信息' }, { title: '付款到平台' }]}
          />
        </div>
        {step === 0 ? (
          <>
            <Table
              rowKey="id"
              size="small"
              scroll={{ x: 'max-content' }}
              columns={columns}
              dataSource={data}
              rowSelection={{ ...rowSelection }}
            />
            <div
              className="bg fixed bottom-0 right-[0] flex h-[120px]  justify-between bg-[#ffffff] pl-[60px]"
              style={{
                boxShadow: 'inset 0px 1px 0px 0px #00000026,0px -4px 8px 0px #0000000C',
                left: `calc(50vw - 712px + ${NAV_WIDTH}px)`,
                paddingRight: 'calc(50vw - 712px)',
              }}
            >
              <div className="flex items-center gap-[20px]">
                <Checkbox checked={isCheckAll} onChange={handleCheckAll}>
                  全选
                </Checkbox>
                <Button onClick={handleBatchDelete}>删除产品</Button>
              </div>
              <div className="flex items-center gap-[20px]">
                <div>
                  数量合计：
                  {checked.reduce((total: number, value: any) => {
                    return total + value.number;
                  }, 0)}
                </div>
                <div>
                  金额：￥
                  {(
                    checked.reduce((total: number, value: any) => {
                      return total + value.totalPrice / 100;
                    }, 0) || 0
                  ).toFixed(2)}
                  (不含运费)
                </div>
                <div>
                  <Button type="primary" onClick={doOrder} disabled={!checked.length}>
                    确定下单
                  </Button>
                </div>
              </div>
            </div>
          </>
        ) : (
          ''
        )}
        {step === 1 ? (
          <div className="flex flex-col gap-[10px]">
            <Card
              title="收货地址"
              bordered={false}
              extra={
                <div className="flex">
                  <div style={{ cursor: 'pointer' }} onClick={() => setAdressShow(true)}>
                    添加收货地址
                  </div>
                </div>
              }
            >
              <div className="flex flex-col gap-[10px]">
                <Radio.Group
                  onChange={(e: any) => {
                    // computedFee(e.target.value);
                    setOrder({ ...order, memberAddressId: e.target.value });
                    commonService
                      .getCustomApi('/member/freightTemplate/getFreightTemplateList', {
                        userAddressId: e.target.value,
                      })
                      .then((res) => {
                        setExpress(res);
                      });
                  }}
                  value={order.memberAddressId}
                >
                  <Space direction="vertical">
                    {orderInfo.memberAddressList.map((item: any) => {
                      return (
                        <Radio value={item.id}>
                          {item.contactName} {item.mobile} {item.pcdText} {item.address}
                        </Radio>
                      );
                    })}
                  </Space>
                </Radio.Group>
              </div>
            </Card>
            <Card title="配送方式" bordered={false}>
              <div className="flex flex-col gap-[10px]">
                <Radio.Group
                  onChange={(e: any) => {
                    const expressItem: any = express.filter((item: any) => {
                      return item.id === e.target.value;
                    })[0];
                    setOrder({
                      ...order,
                      ftId: e.target.value,
                      sendType: expressItem.distriModeId,
                    });
                    commonService
                      .getCustomApi('/member/freightTemplate/getFreightMoney', {
                        ftId: e.target.value,
                        weight: orderInfo.totalWeight,
                      })
                      .then((res) => {
                        setFee(res);
                      });
                  }}
                  value={order.ftId}
                >
                  <Space direction="vertical">
                    {express.map((item: any) => {
                      return (
                        <Radio value={item.id}>
                          {item.distriName}
                          {order.ftId === item.id ? <span>({toYuan(fee)}元)</span> : ''}
                        </Radio>
                      );
                    })}
                  </Space>
                </Radio.Group>
              </div>
            </Card>
            <Card title="商品清单" bordered={false}>
              {orderInfo.shoppingViewList.map((row: any) => {
                return (
                  <div className="flex justify-between">
                    <div className="relative flex gap-[10px]">
                      <div className="h-[120px] w-[120px]">
                        <Image alt={row.goodsName} src={JSON.parse(row.thumbs || '[]')[0]} />
                      </div>

                      {row.thumbs.length > 0 ? (
                        <div className="absolute left-0 top-0 bg-[#FD7901] p-[4px] text-[14px] text-[#ffffff]">
                          两面
                        </div>
                      ) : (
                        ''
                      )}
                      <div className="flex flex-col gap-[5px] text-left text-[#686B73]">
                        <div className="mb-[5px] font-bold text-[#222222]">{row.goodsName}</div>
                        <div>编码：{row.fpId}</div>
                        <div>颜色：{row.color}</div>
                        <div>尺码：{row.size}</div>
                      </div>
                    </div>
                    <div className="flex items-center gap-[20px]">
                      <div className="">
                        原价：<span className="throw-line">{toYuan(row.price)}</span>
                        折扣价：
                        {toYuan(row.discountPrice)}
                      </div>
                      <div>数量：{row.number}</div>
                      <div>小计：{toYuan(row.totalPrice)}</div>
                    </div>
                  </div>
                );
              })}
            </Card>
            {/* <Card
              title="第三方单号"
              bordered={false}
              extra={
                <Input
                  value={order.thirdpartyOrderNumber}
                  onChange={(e: any) =>
                    setOrder({ ...order, thirdpartyOrderNumber: e.taret.value })
                  }
                />
              }
            /> */}
            <Card title="包装方式" bordered={false}>
              <Image
                width={200}
                style={{ display: 'none' }}
                src={pic}
                preview={{
                  visible,
                  src: pic,
                  onVisibleChange: (value) => setVisible(value),
                }}
              />
              <div className="flex gap-[10px]">
                <Radio.Group
                  onChange={(e: any) => {
                    const { value, fee } = e.target;
                    setOrder({
                      ...order,
                      packageId: value,
                      packageFee: fee * orderInfo.totalNumber,
                    });
                  }}
                  value={order.packageId}
                >
                  {/* 2极简包装 1礼盒包装 */}
                  {orderInfo.packages.map((item: any) => {
                    return (
                      <Radio value={item.id} fee={item.fee}>
                        {item.packageType}&nbsp;
                        <QuestionCircleOutlined
                          onClick={() => {
                            setPic(item.pic);
                            setVisible(true);
                          }}
                          style={{ cursor: 'pointer' }}
                        />
                        {`（￥${toYuan(item.fee)}/件）`}
                        {item.id === 1 && order.packageFee
                          ? `包装费：￥${toYuan(order?.packageFee)}`
                          : ''}
                      </Radio>
                    );
                  })}
                </Radio.Group>
              </div>
            </Card>
            <Card title="可用优惠券 | 等级折扣" bordered={false}>
              <div className="flex gap-[10px]">
                {orderInfo.couponList ? (
                  <Radio.Group
                    onChange={(e: any) => {
                      const val = e.target.value;
                      const couponItem = orderInfo.couponList.filter((item: any) => {
                        return item.id === val;
                      })[0];
                      setCoupon(couponItem.money);
                      setOrder({ ...order, couponId: val });
                    }}
                    value={order.couponId}
                  >
                    <Space direction="vertical">
                      {orderInfo.couponList.map((item: any) => {
                        return (
                          <Radio value={item.id}>
                            {item.code} {item.des}
                          </Radio>
                        );
                      })}
                    </Space>
                  </Radio.Group>
                ) : (
                  ''
                )}
                {orderInfo.memberLevel ? (
                  <div>
                    <div>
                      您的身份是分销商，会员等级：{orderInfo.memberLevel.levelName} 折扣：
                      {orderInfo.memberLevel.discount}
                    </div>
                  </div>
                ) : (
                  ''
                )}
              </div>
            </Card>
            <div className="flex flex-col items-end gap-[10]">
              <div>
                费用合计(优惠|折扣)后：
                {toYuan(orderInfo.discountTotalPrice + fee + (order.packageFee || 0) - coupon)}
                （含运费：￥
                {toYuan(fee)}，包装费：￥{toYuan(order.packageFee || '')}）
              </div>
              <div>
                <Button
                  type="primary"
                  className="mt-[20px] h-[50px] w-[140px]"
                  onClick={() => submitOrder()}
                >
                  提交
                </Button>
              </div>
            </div>
          </div>
        ) : (
          ''
        )}

        {step === 2 ? (
          <div className="flex flex-col gap-[10px]">
            <Card title="付款信息" bordered={false}>
              <div className="flex justify-between">
                <div>订单号: {payData.orderNumber}</div>
                <div>应付金额: ￥{toYuan(payData.totalMoney)}</div>
              </div>
            </Card>
            <Card title="付款方式" bordered={false}>
              <div className="flex flex-col gap-[20px]">
                <Radio.Group
                  onChange={(e: any) => {
                    setPayType(e.target.value);
                  }}
                  value={payType}
                >
                  <Space direction="horizontal">
                    <Radio value="wechat">微信</Radio>
                    <Radio value="alipay">支付宝</Radio>
                    <Radio value="balance">余额（￥{toYuan(payData.balance)}）</Radio>
                  </Space>
                </Radio.Group>
                <div>
                  <Button type="primary" className="h-[50px] w-[140px]" onClick={() => toPay()}>
                    去付款
                  </Button>
                </div>
              </div>
            </Card>
          </div>
        ) : (
          ''
        )}
      </Card>
      <Modal
        title="扫码支付"
        open={showPay}
        onCancel={() => setShowPay(false)}
        onOk={() => setShowPay(false)}
        centered
      >
        <div className="flex items-center justify-center">
          <Image src={`data:image/jpg;base64,${payUrl}`} preview={false} />
        </div>
      </Modal>

      <AddressModal
        formValue={{}}
        show={addressShow}
        title="新增地址"
        onCancel={() => setAdressShow(false)}
        onOk={handleAddressModalClose}
        tree={tree}
      />
    </Space>
  );
}
